package com.baimawangzi.recovery.util.dbutil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


public class QueryRunner {
    private Connection conn;//属性

    public QueryRunner(Connection conn){
        this.conn = conn;
    }

    //封装通用的DML语句的方法(insert、update、delete)  executeUpdate()---->int
    public int update(String sql,Object... params){
        //可变参数的作用：给SQL中的?进行赋值
        //Connection conn = DBConnection.getConn();
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            //给SQL语句中的?赋值
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i+1,params[i]);
            }
            //执行
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }


    //封装通用的DQL语句的方法(select)
    public <T> List<T> query(String sql , ResultHandler<T> rh, Object... params){
        ResultSet rs=null;
        //Connection conn = DBConnection.getConn();
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i+1,params[i]);
            }
            rs = ps.executeQuery();
            return rh.handler(rs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if(rs!=null){//防止空指针异常
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return null;
    }
}

